import { Component, OnInit, APP_ID, Inject } from '@angular/core';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { SelectItem } from 'primeng/primeng';
import { SendContextContent, SubContextTypeChanged, HelloworldContext, getAllContextTypes, getContextDesc, getUUID, IdentityContext } from '../../utils/sample.context';
import { IContextBroker, UUID, IContext, ICONTEXT_BROKER_TOKEN } from '../../../../src/index';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-app-context-broker-basic',
  templateUrl: './app-context-broker-basic.component.html',
  styleUrls: ['./app-context-broker-basic.component.scss']
})
export class AppContextBrokerBasicComponent implements OnInit {
  subContextForm: FormGroup;
  sendContextForm: FormGroup;
  subContextTypes: SelectItem[];
  sendContextTypes: SelectItem[];
  receivedContexts: string[] = [];
  private _compId = getUUID();

  constructor(
    @Inject(ICONTEXT_BROKER_TOKEN) private _broker: IContextBroker,
    private _fb: FormBuilder,
    @Inject(APP_ID) private _appId: string) {

  }

  ngOnInit() {
    this.initContextSelections();
    this.createForm();
  }

  initContextSelections() {
    this.subContextTypes = getAllContextTypes();
    this.sendContextTypes = getAllContextTypes();
  }

  createForm() {
    this.subContextForm = this._fb.group({
      subContextType: this.subContextTypes[0],
    });

    this.sendContextForm = this._fb.group({
      sendContextType: this.sendContextTypes[0],
      sendContextContent: JSON.stringify(this.sendContextTypes[0].value.default, null, 2),
    });
  }

  sendContextTypeChanged($event: any) {
    let sendContextType = this.sendContextForm.get('sendContextType').value;
    this.sendContextForm.patchValue({
      sendContextContent: JSON.stringify(sendContextType.default, null, 2),
    });
  }

  onSubmitSub() {
    let selectedContextType = this.subContextForm.get('subContextType').value;
    let index = this.subContextTypes.findIndex(a => a.value === selectedContextType);
    this.subContextTypes.splice(index, 1);
    debugger;
    this._broker.registerListener(selectedContextType.type, {
      next: (c: any) => {
        let newContext = getContextDesc(c);
        this.receivedContexts = [newContext].concat(this.receivedContexts);
      },
      error: (error: any) => {
        console.log(error);
      },
      complete: () => {
      }
    });


  }

  onSubmitSend() {
    let sendContext = this.sendContextForm.value;
    let context = JSON.parse(sendContext.sendContextContent) as IdentityContext;
    context.fromApplication = this._appId;
    context.fromComponent = this._compId;

    this._broker.registerProvider(context);
  }
}
